<template>
  <div>
    <a-card :bordered="false" :bodyStyle="{ height: '100%' }" :style="{ height: '100%' }">
      <a-card-grid style="width:25%;text-align:'center';height:100%">
        <div style="height:100%">
          <a-input-search style="margin-bottom: 8px" v-model="searchValue" placeholder="请输入路由标题查询" @change="onTreeSearchChange" />
          <div class="hh-scroll-hover" style="height:420px">
            <div>
              <a-tree
                showLine
                @expand="onExpand"
                :expandedKeys="expandedKeys"
                :selectedKeys="selectedKeys"
                :autoExpandParent="autoExpandParent"
                :treeData="routerList"
                draggable
                @dragenter="onDragEnter"
                @drop="onDrop"
                @select="this.onRouterTreeSelect"
              >
                <template slot="title" slot-scope="{title}">
                  <span v-if="title.indexOf(searchValue) > -1">
                    {{ title.substr(0, title.indexOf(searchValue)) }}
                    <span class="search-tree-color">{{ searchValue }}</span>
                    {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span v-else>{{ title }}</span>
                </template>
              </a-tree>
            </div>
          </div>
        </div>
      </a-card-grid>
      <a-card-grid style="width:75%;textAlign:'center';height:100%">
          <a-tabs defaultActiveKey="baseInfo" @change="tabsChange">
            <a-tab-pane tab="基础信息" key="baseInfo" forceRender>
            </a-tab-pane>
            <a-tab-pane tab="角色权限列表" key="roleList" forceRender>
            </a-tab-pane>
            <a-tab-pane tab="功能权限列表" key="functionList" forceRender>
            </a-tab-pane>
            <a-tab-pane tab="用户权限列表" key="userList" forceRender>
            </a-tab-pane>
          </a-tabs>
          <div class="hh-scroll-hover" v-if="tabKey==='baseInfo'" style="height:400px;">
            <router-form ref="routerPage" />
          </div>
          <div  v-if="tabKey==='roleList'">
            <div class="table-page-search-wrapper">
                <a-form layout="horizontal" >
                  <a-row :gutter="8">
                    <a-col :md="9" :sm="24">
                      <a-form-item label="角色名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                        <a-input v-model="queryRoleParam.roleName" placeholder="支持模糊查询"/>
                      </a-form-item>
                    </a-col>
                    <a-col :md="9" :sm="24">
                      <a-form-item label="角色类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                        <a-select v-model="queryRoleParam.roleTypes" mode="multiple" placeholder="请选择" allowClear >
                          <a-select-option v-for="item in dictData.roleType" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } ">
                        <a-button type="primary" @click="() =>{this.findRoleListBtn()}">查询</a-button>
                        <a-button style="margin-left: 8px" @click="() => {this.clearRoleAll()}">重置</a-button>
                      </span>
                    </a-col>
                  </a-row>
                </a-form>
              </div>
              <vxe-grid
                resizable
                show-overflow
                ref="roleListTable"
                stripe
                border
                :auto-resize="true"
                highlight-hover-row
                highlight-current-row
                highlight-hover-column
                highlight-current-column
                highlight-cell
                height="337px"
                size="small"
                row-id="roleId"
                :columns="roleColumn"
                :data="roleTableData"
                :loading="roleLoading"
                :start-index="(roleTablePage.currentPage - 1) * roleTablePage.pageSize"
                :pager-config="roleTablePage"
                @page-change="handleRolePageChange"
              >
            </vxe-grid>
          </div>
          <vxe-grid
            v-if="tabKey==='functionList'"
            resizable
            show-overflow
            :auto-resize="true"
            ref="functionListTable"
            stripe
            border
            highlight-hover-row
            highlight-current-row
            highlight-hover-column
            highlight-current-column
            height="337px"
            size="small"
            row-id="funcId"
            :columns="functionColumn"
            :data="functionTableData"
            :loading="functionLoading"
          >
          </vxe-grid>
        <div  v-if="tabKey==='userList'">
          <div class="table-page-search-wrapper">
            <a-form layout="horizontal" >
              <a-row :gutter="8">
                <a-col :md="9" :sm="24">
                  <a-form-item label="用户名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model="queryUserParam.userName" placeholder="支持模糊查询"/>
                  </a-form-item>
                </a-col>
                <a-col :md="9" :sm="24">
                  <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model="queryUserParam.fullName" placeholder="支持模糊查询"/>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } ">
                    <a-button type="primary" @click="() =>{this.findUserListBtn()}">查询</a-button>
                    <a-button style="margin-left: 8px" @click="() => {this.clearUserAll()}">重置</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <vxe-grid
            resizable
            show-overflow
            ref="userListTable"
            stripe
            border
            :auto-resize="true" 
            highlight-hover-row
            highlight-current-row
            highlight-hover-column
            highlight-current-column
            highlight-cell
            height="337px"
            size="small"
            row-id="userId"
            :columns="userColumn"
            :data="userTableData"
            :loading="userLoading"
            :start-index="(userTablePage.currentPage - 1) * userTablePage.pageSize"
            :pager-config="userTablePage"
            @page-change="handleUserPageChange"
            :checkbox-config="{reserve: true, checkMethod}"
          >
          </vxe-grid>
        </div>
      </a-card-grid>
      <a-modal
        title="关联功能信息"
        centered
        style="top: 20px;"
        width="380px"
        destroyOnClose
        v-model="functionVisible"
        cancelText="关闭"
        okText="保存"
        @ok="saveFunction"
      >
        <div style="height:100%">
          <a-input-search style="margin-bottom: 8px" v-model="searchFunctionValue" placeholder="请输入功能标题查询" @change="onFunctionTreeSearchChange" />
           <div class="hh-scroll-hover" style="height:400px">
                <a-tree
                  showLine
                  checkable
                  @expand="onExpandFunction"
                  :expandedKeys="expandedFunctionKeys"
                  :selectedKeys="selectedFunctionKeys"
                  :autoExpandParent="autoExpandFunctionParent"
                  :treeData="functionTreeList"
                  v-model="checkedFunctionKeys"
                >
                  <template slot="title" slot-scope="{title}">
                    <span v-if="title.indexOf(searchFunctionValue) > -1">
                      {{ title.substr(0, title.indexOf(searchFunctionValue)) }}
                      <span class="search-tree-color">{{ searchFunctionValue }}</span>
                      {{ title.substr(title.indexOf(searchFunctionValue) + searchFunctionValue.length) }}
                    </span>
                    <span v-else>{{ title }}</span>
                  </template>
                </a-tree>
          </div>
        </div>
      </a-modal>
      <a-modal
        title="单独添加用户"
        centered
        style="top: 20px;"
        width="85%"
        destroyOnClose
        v-model="routerUservisible"
        cancelText="关闭"
        okText="保存"
        @ok="saveUser"
      >
        <router-user-form ref="routerUserPage" :routerInfo="routerInfo" />
      </a-modal>
      <a-modal
        title="角色授权"
        centered
        style="top: 20px;"
        width="85%"
        destroyOnClose
        cancelText="关闭"
        okText="保存"
        v-model="roleVisible"
        @ok="saveRole"
      >
        <router-role-form ref="routerRolePage" :routerInfo="routerInfo" />
      </a-modal>
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <a-button style="margin-left: 8px;" v-if="infoFlag" type="primary" icon="plus" @click="() =>{this.routerAdd()}">同级新增</a-button>
      <a-button style="margin-left: 8px;" v-if="infoFlag" type="primary" icon="plus-circle" @click="() =>{this.childRouterAdd()}">子级新增</a-button>
      <a-button style="margin-left: 8px;" v-if="infoFlag" type="primary" icon="edit" @click="() =>{this.saveRouter()}">保存</a-button>
      <a-button style="margin-left: 8px" v-if="infoFlag" type="danger" icon="minus" @click="() =>{this.deleteRouter()}">删除</a-button>
      <a-button
        style="margin-left: 8px"
        ghost
        v-if="infoFlag"
        type="primary"
        icon="minus-circle"
        @click="() =>{this.clearRouterCache()}">清除缓存</a-button>
      <a-button style="margin-left: 8px;" v-if="functionFlag" type="primary" icon="plus" @click="() =>{this.openFunctionModel()}">关联功能</a-button>
      <a-button style="margin-left: 8px;" v-if="userFlag" type="primary" icon="plus" @click="() =>{this.openRouetUserModel()}">添加用户</a-button>
      <a-button style="margin-left: 8px" v-if="userFlag" type="danger" icon="minus" @click="() =>{this.deleteUser()}">删除用户</a-button>
      <a-button style="margin-left: 8px;" v-if="roleFlag" type="primary" icon="plus" @click="() =>{this.openRoleModel()}">添加角色</a-button>
      <a-button style="margin-left: 8px;" v-if="roleFlag" type="danger" icon="minus" @click="() =>{this.deleteRole()}">删除角色</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import { getBatchDict,getFunctionTreeList,getRouterTreeList, getRouterInfo, getRouterUserList, getRouterFunctionList, addRouter, editRouter, deleteRouter, moveRouter, clearRouterCache, saveRouterFunc, saveRouterUser, deleteRouterUser, getRouterRoleList, saveRouterRole, deleteRouterRole } from "@/services/system/api"
import FooterToolBar from '@/components/FooterToolbar'
import RouterForm from '@/pages/system/form/RouterForm'
import RouterUserForm from '@/pages/system/form/RouterUserForm'
import RouterRoleForm from '@/pages/system/form/RouterRoleForm'
import modal from 'ant-design-vue/es/modal'
import { loop, loopParentKey } from '@/utils/util'
const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'processing',
    text: '启用'
  }
}
const flagMap = {
  0: {
    status: 'default',
    text: '否'
  },
  1: {
    status: 'success',
    text: '是'
  }
}
function loopCheckDisable (data) {
  data.forEach((item) => {
    if (item.nodeType === '0') {
      item.disabled = true
      if(item.children){
        loopCheckDisable(item.children)
      }
    }
  })
}
function loopExpandKey (data, keys, expandKeys) {
  let flag = false
  data.forEach((item) => {
    let itemFlag = false
    const funcId = item.key
    keys.some((item) => {
      if (funcId === item) {
        itemFlag = true
        return true
      }
    })
    if (item.children) {
      const childFlag = loopExpandKey(item.children, keys, expandKeys)
      if (childFlag) {
        itemFlag = true
      }
    }
    if (itemFlag) {
      flag = true
      expandKeys.push(item.key)
    }
  })
  return flag
}
export default {
  name: 'RouterManager',
  components: {
    FooterToolBar,
    RouterForm,
    RouterUserForm,
    RouterRoleForm
  },
  data () {
    return {
      description: '页面管理',
      // 用户查询条件
      queryUserParam: {},
      // 角色查询条件
      queryRoleParam: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      dictData: {},
      tabKey: 'baseInfo',
      // 基础信息操作按钮是否显示
      infoFlag: true,
      routerInfo: null,
      // 功能列表操作按钮是否显示
      functionFlag: false,
      // 用户列表操作按钮是否显示
      userFlag: false,
      // 角色列表操作按钮是否显示
      roleFlag: false,
      // 路由树
      expandedKeys: [],
      selectedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      routerList: [],
      infoButtonType: '9',
      // 功能列表参数
      functionTableData: [],
      functionLoading: false,
      functionColumn: [
        { type: 'seq', minWidth: 50, fixed: 'left', align: 'center', title: '序号' },
        { field: 'funcId', title: '功能Id', visible: false, fixed: 'left', align: 'center', minWidth: 150 },
        { field: 'funcCode', title: '功能编号', fixed: 'left', align: 'center', minWidth: 150 },
        { field: 'funcTitle', title: '功能标题', align: 'center', minWidth: 200 },
        { field: 'funcName', title: '功能类型', align: 'center', minWidth: 100 },
        { field: 'status', title: '状态', align: 'center', minWidth: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } },
        { field: 'classPath', title: '所属类', align: 'center', minWidth: 200 },
        { field: 'method', title: '所属方法', align: 'center', minWidth: 100 },
        { field: 'publicFlag', title: '是否公共', align: 'center', minWidth: 80, slots: { default: ({ row }) => { return [this.formatflag(row.publicFlag)] } } },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, minWidth: 250 }
      ],
      // 功能列表参数
      userTableData: [],
      userLoading: false,
      userTablePage: {
        total: 0,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20
      },
      userColumn: [
        { type: 'checkbox', width: 50, fixed: 'left' },
        { type: 'seq', width: 50, fixed: 'left', align: 'center', title: '序号' },
        { field: 'userId', title: '用户Id', visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'userName', title: '用户名', align: 'center', width: 150 },
        { field: 'fullName', title: '姓名', align: 'center', width: 150 },
        { field: 'privilegeSource', title: '授权来源ID', visible: false, align: 'center', width: 150 },
        { field: 'sourceName', title: '授权来源', align: 'center', width: 150 },
        { field: 'userType', title: '用户类型key', visible: false, align: 'center', width: 150 },
        { field: 'userTypeName', title: '用户类型', align: 'center', width: 150 },
        { field: 'status', title: '状态', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } }
      ],
      // 关联功能弹出框
      functionVisible: false,
      functionTreeList: [],
      expandedFunctionKeys: [],
      selectedFunctionKeys: [],
      searchFunctionValue: '',
      autoExpandFunctionParent: true,
      checkedFunctionKeys: [],
      routerUservisible: false,
      // 角色列表参数
      // 角色授权
      roleVisible: false,
      roleTableData: [],
      roleLoading: false,
      roleTablePage: {
        total: 0,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20
      },
      roleColumn: [
        { type: 'checkbox', width: 50, fixed: 'left' },
        { type: 'seq', width: 50, fixed: 'left', align: 'center', title: '序号' },
        { field: 'roleId', title: '角色Id', visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'roleName', title: '角色名称', align: 'center', fixed: 'left', width: 200 },
        { field: 'parentId', title: '父角色Id', visible: false, align: 'center', width: 200 },
        { field: 'roleType', title: '角色类型', visible: false, align: 'center', width: 100 },
        { field: 'roleTypeName', title: '角色类型', align: 'center', width: 100 },
        { field: 'status', title: '状态', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 250 }
      ]
    }
  },
  created () {
    // 初始化数据
    this.findRouterTreeList()
    const params = {}
    params.dictFields = 'roleType'
    this.$http.post(getBatchDict,params).then(res => {
      this.dictData = res.result
    })
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  methods: {
    // 树节点选择事件
    onRouterTreeSelect (selectedKeys) {
      this.infoButtonType = '3'
      //this.$refs.routerPage.setDisabled(false)
      this.selectedKeys = selectedKeys
      this.findRouterInfo()
    },
    findRouterInfo () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        const routerId = this.selectedKeys[0]
        // 获取节点相关信息
        const params = {}
        params.routerId = routerId
        setTimeout(() => {
          this.$http.post(getRouterInfo,params).then((res) => {
            this.routerInfo = res.result.routerInfo
            if (this.functionFlag) {
              this.functionTableData = res.result.functionList
            }
            if (this.userFlag) {
              this.findUserList()
            }
            if (this.roleFlag) {
              this.findRoleList()
            }
            if(this.functionFlag==false&&this.userFlag==false&&this.roleFlag==false){
              // 赋值子组件信息
              this.$refs.routerPage.setInitDate(res.result.routerInfo)
            }
          }).catch(() => {
          })
        }, 50)
      }
    },
    findUserListBtn () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.userTablePage.pageNum = 1
        this.userTablePage.currentPage = 1
        this.findUserList()
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    findUserList () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.userloading = true
        const params = Object.assign(this.queryUserParam, this.userTablePage)
        params.routerId = this.selectedKeys[0]
        this.$http.post(getRouterUserList,params).then((res) => {
          this.userTableData = res.result.list
          this.userTablePage.total = res.result.total
          this.userTablePage.pageNum = res.result.pageNum
          this.userTablePage.currentPage = res.result.pageNum
          this.userTablePage.pageSize = res.result.pageSize
          this.userLoading = false
        }).catch(() => {
          this.userLoading = false
        })
      }
    },
    findFunctionList () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.userloading = true
        const params = {}
        params.routerId = this.selectedKeys[0]
        params.nodeType = '1'
        setTimeout(() => {
          this.$http.post(getRouterFunctionList,params).then((res) => {
            this.functionTableData = res.result
            this.functionLoading = false
          }).catch(() => {
            this.functionLoading = false
          })
        }, 50)
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onTreeSearchChange (e) {
      const value = e.target.value
      if (value) {
        const data = [...this.routerList]
        const expandedKeys = []
        loopParentKey(data, value, expandedKeys)
        this.expandedKeys = expandedKeys
        this.searchValue = value
        this.autoExpandParent = true
      }
    },
    tabsChange (key) {
      this.tabKey=key
      if (key === 'baseInfo') {
        this.infoFlag = true
        this.functionFlag = false
        this.userFlag = false
        this.roleFlag = false
        this.findRouterInfo()
      } else if (key === 'functionList') {
        this.infoFlag = false
        this.functionFlag = true
        this.userFlag = false
        this.roleFlag = false
        this.findFunctionList()
      } else if (key === 'userList') {
        this.infoFlag = false
        this.functionFlag = false
        this.userFlag = true
        this.roleFlag = false
        this.findUserList()
      } else if (key === 'roleList') {
        this.findRoleList()
        this.infoFlag = false
        this.roleFlag = true
        this.functionFlag = false
        this.userFlag = false
      }
    },
    findRouterTreeList () {
      const params = {}
      params.searchText = this.searchValue
      setTimeout(() => {
        this.$http.post(getRouterTreeList,params).then((res) => {
          this.routerList = res.result.routerList
          this.expandedKeys = res.result.expandedKeys
        }).catch(() => {
        })
      }, 50)
    },
    formatStatus (cellValue) {
      if (cellValue) {
        const text = statusMap[cellValue].text
        const status = statusMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    formatflag (cellValue) {
      if (cellValue) {
        const text = flagMap[cellValue].text
        const status = flagMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    saveRouter () {
      // 表单验证
      const { $refs: { routerPage } } = this
      const routerForm = new Promise((resolve, reject) => {
        routerPage.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })
      this.errors = []
      Promise.all([routerForm]).then(values => {
        if (values && values.length > 0) {
          const router = values[0]
          if (router.hidden) {
            router.hidden = '1'
          } else {
            router.hidden = '0'
          }
          if (router.hideChildrenInMenu) {
            router.hideChildrenInMenu = '1'
          } else {
            router.hideChildrenInMenu = '0'
          }
          if (router.keepAlive) {
            router.keepAlive = '1'
          } else {
            router.keepAlive = '0'
          }
          if (router.hiddenHeaderContent) {
            router.hiddenHeaderContent = '1'
          } else {
            router.hiddenHeaderContent = '0'
          }
          if (router.hiddenBreadcrumb) {
            router.hiddenBreadcrumb = '1'
          } else {
            router.hiddenBreadcrumb = '0'
          }
          if (router.disabled) {
            router.disabled = '1'
          } else {
            router.disabled = '0'
          }
          if (router.logFlag) {
            router.logFlag = '1'
          } else {
            router.logFlag = '0'
          }
          if (router.rollbackFlag) {
            router.rollbackFlag = '1'
          } else {
            router.rollbackFlag = '0'
          }
          if (router.publicFlag) {
            router.publicFlag = '1'
          } else {
            router.publicFlag = '0'
          }
          if (router.auditFlag) {
            router.auditFlag = '1'
          } else {
            router.auditFlag = '0'
          }
          if (router.spanRollbackFlag) {
            router.spanRollbackFlag = '1'
          } else {
            router.spanRollbackFlag = '0'
          }
          if (router.routerId) {
            setTimeout(() => {
              this.$http.post(editRouter,router).then((res) => {
                modal.info({ title: '成功提示', content: '修改成功' })
                let oldTitle = ''
                if (this.routerInfo) {
                  oldTitle = this.routerInfo.title
                }
                this.routerInfo = null
                // 更新树节点
                if (oldTitle !== res.result.title) {
                  const dragKey = res.result.routerId
                  const data = [...this.routerList]
                  let dragObj
                  let ar
                  let i
                  loop(data, dragKey, (item, index, arr) => {
                    ar = arr
                    i = index
                    dragObj = item
                  })
                  dragObj.title = res.result.title
                  dragObj.value = res.result.title
                  ar.splice(i, 1, dragObj)
                  this.routerList = data
                  const newSelect = []
                  newSelect.push(dragKey)
                  this.selectedKeys = newSelect
                }
                this.routerInfo = res.result
              }).catch(() => {
                // this.$refs.routerPage.setInitDate(this.routerInfo)
              })
            }, 50)
          } else {
            setTimeout(() => {
              this.$http.post(addRouter,router).then((res) => {
                modal.info({ title: '成功提示', content: '新增成功' })
                const data = [...this.routerList]
                const dragKey = this.routerInfo.routerId
                const dropKey = res.result.parentId
                const routerId = res.result.routerId
                const dragObj = {}
                dragObj.key = res.result.routerId
                dragObj.title = res.result.title
                dragObj.value = res.result.title
                dragObj.parentKey = res.result.parentId
                dragObj.icon = res.result.icon
                dragObj.scopedSlots = { title: 'title' }
                if (this.infoButtonType === '1') {
                  // 同级新增
                  let ar
                  let i
                  loop(data, dragKey, (item, index, arr) => {
                    ar = arr
                    i = index
                  })
                  ar.splice(i, 0, dragObj)
                } else if (this.infoButtonType === '2') {
                  // 子级新增
                  loop(data, dropKey, item => {
                    item.children = item.children || []
                    if (!item.expanded) {
                      item.expanded = true
                    }
                    // where to insert 示例添加到尾部，可以是随意位置
                    item.children.push(dragObj)
                  })
                }
                this.routerInfo = null
                this.routerList = data
                this.$refs.routerPage.setInitDate(res.result)
                const newSelect = []
                newSelect.push(routerId)
                this.selectedKeys = newSelect
                this.routerInfo = res.result
                const newExpandedKeys = this.expandedKeys
                if (newExpandedKeys && newExpandedKeys.length > 0) {
                  if (newExpandedKeys.indexOf(dropKey) <= 0) {
                    newExpandedKeys.push(dropKey)
                    this.expandedKeys = newExpandedKeys
                  }
                }
              }).catch(() => {
              })
            }, 50)
          }
        }
      }).catch(() => {
        const errors = Object.assign({}, routerPage.form.getFieldsError())
        const tmp = { ...errors }
        this.errorList(tmp)
      })
    },
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0]
        }))
    },
    routerAdd () {
      if (this.routerInfo) {
        this.infoButtonType = '1'
        const params = {}
        params.parentId = this.routerInfo.parentId
        params.parentTitle = this.routerInfo.parentTitle
        params.icon = this.routerInfo.icon
        params.component = this.routerInfo.component
        params.routerId = ''
        params.orderNo = this.routerInfo.orderNo
        params.rate = this.routerInfo.rate
        params.hidden = '0'
        this.$refs.routerPage.setInitDate(params)
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    childRouterAdd () {
      if (this.routerInfo) {
        this.infoButtonType = '2'
        const params = {}
        params.parentId = this.routerInfo.routerId
        params.parentTitle = this.routerInfo.title
        params.icon = this.routerInfo.icon
        params.routerId = ''
        params.orderNo = ''
        let rate = this.routerInfo.rate
        if (rate) {
          rate = rate + 1
        } else {
          rate = 1
        }
        params.rate = rate
        params.hidden = '0'
        this.$refs.routerPage.setInitDate(params)
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    deleteRouter () {
      if (this.routerInfo) {
        const params = {}
        params.routerId = this.routerInfo.routerId
        setTimeout(() => {
          this.$http.post(deleteRouter,params).then(() => {
            modal.info({ title: '成功提示', content: '删除成功' })
            const data = [...this.routerList]
            loop(data, this.routerInfo.routerId, (item, index, arr) => {
              arr.splice(index, 1)
            })
            this.routerList = data
            this.selectedKeys = []
            this.routerInfo = null
            this.infoButtonType = '9'
            this.$refs.routerPage.setInitDate(null)
            this.$refs.routerPage.setDisabled(true)
          }).catch(() => {
          })
        }, 100)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要删除的数据' })
      }
    },
    onDragEnter (info) {
      console.log(info)
      // expandedKeys 需要受控时设置
      // this.expandedKeys = info.expandedKeys
    },
    onDrop (info) {
      console.log(info)
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const params = {}
      params.dropKey = dropKey
      params.dragKey = dragKey
      params.dropPosition = dropPosition
      setTimeout(() => {
        this.$http.post(moveRouter,params).then((res) => {
          const data = [...this.routerList]
          // Find dragObject
          let dragObj
          loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1)
            dragObj = item
          })
          if (!info.dropToGap) {
            // Drop on the content
            loop(data, dropKey, item => {
              item.children = item.children || []
              // where to insert 示例添加到尾部，可以是随意位置
              item.children.push(dragObj)
            })
          } else if (
            (info.node.children || []).length > 0 && // Has children
            info.node.expanded && // Is expanded
            dropPosition === 1 // On the bottom gap
          ) {
            loop(data, dropKey, item => {
              item.children = item.children || []
              // where to insert 添加到第一行
              item.children.unshift(dragObj)
            })
          } else {
            let ar
            let i
            loop(data, dropKey, (item, index, arr) => {
              ar = arr
              i = index
            })
            if (dropPosition === -1) {
              ar.splice(i, 0, dragObj)
            } else {
              ar.splice(i + 1, 0, dragObj)
            }
          }
          this.routerList = data
          this.routerInfo = res.result
          this.$refs.routerPage.setInitDate(res.result)
        }).catch(() => {
        })
      }, 50)
    },
    clearRouterCache () {
      if (this.routerInfo) {
        const params = {}
        params.routerId = this.routerInfo.routerId
        setTimeout(() => {
          this.$http.post(clearRouterCache,params).then(() => {
            modal.info({ title: '成功提示', content: '清除缓存成功' })
          }).catch(() => {
          })
        }, 100)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要清除缓存的数据' })
      }
    },
    handleUserPageChange ({ currentPage, pageSize }) {
      this.userTablePage.pageNum = currentPage
      this.userTablePage.currentPage = currentPage
      this.userTablePage.pageSize = pageSize
      this.findUserList()
    },
    openFunctionModel () {
      // 打开添加功能页面
      if (this.routerInfo) {
        const nodeType = this.routerInfo.nodeType
        if (nodeType === '0') {
          modal.warn({ title: '提示', content: '节点不能关联功能' })
          return
        }
        // 获取功能树
        this.findFunctionTreeList()
        setTimeout(() => {
          // 添加选中节点
          this.functionVisible = true
        }, 100)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要关联功能的数据' })
      }
    },
    onExpandFunction (expandedKeys) {
      this.expandedFunctionKeys = expandedKeys
      this.autoExpandFunctionParent = false
    },
    saveFunction () {
      // 获取选中的路由信息
      if (this.routerInfo) {
        const params = {}
        params.funcIds = this.checkedFunctionKeys
        params.routerId = this.routerInfo.routerId
        setTimeout(() => {
          this.$http.post(saveRouterFunc,params).then(() => {
            this.findFunctionList()
            this.functionVisible = false
          }).catch(() => {
          })
        }, 50)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要关联功能的数据' })
      }
    },
    findFunctionTreeList () {
      this.searchFunctionValue = ''
      const params = {}
      params.searchText = this.searchFunctionValue
      setTimeout(() => {
        this.$http.post(getFunctionTreeList,params).then((res) => {
          const data = [...res.result.functionList]
          if (data) {
            loopCheckDisable(data)
            this.functionTreeList = data
            this.checkedFunctionKeys = []
            this.expandedFunctionKeys = res.result.expandedKeys
            if (this.functionTableData && this.functionTableData.length > 0) {
              // 设置选中节点
              const checkedKeys = []
              this.functionTableData.forEach((item) => {
                checkedKeys.push(item.funcId)
              })
              // 设置展开节点
              const expandedFunctionKeys = []
              loopExpandKey(data, checkedKeys, expandedFunctionKeys)
              this.checkedFunctionKeys = checkedKeys
              this.expandedFunctionKeys = expandedFunctionKeys
              this.autoExpandFunctionParent = true
            }
          }
        }).catch(() => {
        })
      }, 10)
    },
    onFunctionTreeSearchChange (e) {
      const value = e.target.value
      if (value) {
        const data = [...this.functionTreeList]
        const expandedKeys = []
        loopParentKey(data, value, expandedKeys)
        this.expandedFunctionKeys = expandedKeys
        this.searchFunctionValue = value
        this.autoExpandFunctionParent = true
      }
    },
    checkMethod ({ row }) {
      // 勾选框是否可操作
      const privilegeSource = row.privilegeSource
      if (privilegeSource === 'alone') {
        return true
      } else {
        return false
      }
    },
    openRouetUserModel () {
      // 打开添加用户页面
      if (this.routerInfo) {
        const nodeType = this.routerInfo.nodeType
        if (nodeType === '0') {
          modal.warn({ title: '提示', content: '不能选择节点操作' })
          return
        }
        this.routerUservisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的路由' })
      }
    },
    saveUser () {
      const sysIds = this.$refs.routerUserPage.functionCheckedKeys
      const users = this.$refs.routerUserPage.userChecked
      const routerId = this.routerInfo.routerId
      if (users) {
        if (users.length <= 0) {
          modal.warn({ title: '提示', content: '请先勾选需要授权的用户' })
          return false
        }
      } else {
        modal.warn({ title: '提示', content: '请先勾选需要授权的用户' })
        return false
      }
      const userIds = []
      users.forEach((item) => {
        userIds.push(item.userId)
      })
      const params = {}
      params.routerId = routerId
      params.sysIds = sysIds
      params.userIds = userIds
      setTimeout(() => {
        this.$http.post(saveRouterUser,params).then(() => {
          modal.info({ title: '成功提示', content: '授权成功' })
          this.routerUservisible = false
          this.findUserList()
        }).catch(() => {
        })
      }, 10)
    },
    deleteUser () {
      if (this.routerInfo) {
        const nodeType = this.routerInfo.nodeType
        if (nodeType === '0') {
          modal.warn({ title: '提示', content: '不能选择节点操作' })
          return
        }
        const checkedUser = this.$refs.userListTable.getCheckboxRecords()
        const selectReserveRecords = this.$refs.userListTable.getCheckboxReserveRecords()
        const userIds = []
        if (checkedUser && checkedUser.length > 0) {
          checkedUser.forEach((item) => {
            userIds.push(item.userId)
          })
        }
        if (selectReserveRecords && selectReserveRecords.length > 0) {
          selectReserveRecords.forEach((item) => {
            userIds.push(item.userId)
          })
        }
        if (userIds.length > 0) {
          const params = {}
          params.userIds = userIds
          params.routerId = this.routerInfo.routerId
          setTimeout(() => {
            this.$http.post(deleteRouterUser,params).then(() => {
              modal.info({ title: '成功提示', content: '删除成功' })
              this.findUserList()
            }).catch(() => {
            })
          }, 10)
        } else {
          modal.warn({ title: '提示', content: '请先勾选需要删除的用户' })
        }
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的路由' })
      }
    },
    findRoleListBtn () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.roleTablePage.pageNum = 1
        this.roleTablePage.currentPage = 1
        this.findRoleList()
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    findRoleList () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.roleloading = true
        const params = Object.assign(this.queryRoleParam, this.roleTablePage)
        params.routerId = this.selectedKeys[0]
        this.$http.post(getRouterRoleList,params).then((res) => {
          this.roleTableData = res.result.list
          this.roleTablePage.total = res.result.total
          this.roleTablePage.pageNum = res.result.pageNum
          this.roleTablePage.currentPage = res.result.pageNum
          this.roleTablePage.pageSize = res.result.pageSize
          this.roleLoading = false
        }).catch(() => {
          this.roleLoading = false
        })
      }
    },
    openRoleModel () {
      if (this.routerInfo) {
        const nodeType = this.routerInfo.nodeType
        if (nodeType === '0') {
          modal.warn({ title: '提示', content: '不能选择节点操作' })
          return
        }
        this.roleVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的路由' })
      }
    },
    handleRolePageChange ({ currentPage, pageSize }) {
      this.roleTablePage.pageNum = currentPage
      this.roleTablePage.currentPage = currentPage
      this.roleTablePage.pageSize = pageSize
      this.findRoleList()
    },
    saveRole () {
      const sysIds = this.$refs.routerRolePage.functionCheckedKeys
      const roles = this.$refs.routerRolePage.roleChecked
      const routerId = this.routerInfo.routerId
      if (roles) {
        if (roles.length <= 0) {
          modal.warn({ title: '提示', content: '请先勾选需要授权的角色' })
          return false
        }
      } else {
        modal.warn({ title: '提示', content: '请先勾选需要授权的角色' })
        return false
      }
      const roleIds = []
      roles.forEach((item) => {
        roleIds.push(item.roleId)
      })
      const params = {}
      params.routerId = routerId
      params.sysIds = sysIds
      params.roleIds = roleIds
      setTimeout(() => {
        this.$http.post(saveRouterRole,params).then(() => {
          modal.info({ title: '成功提示', content: '授权成功' })
          this.roleVisible = false
          this.findRoleList()
        }).catch(() => {
        })
      }, 10)
    },
    deleteRole () {
      if (this.routerInfo) {
        const nodeType = this.routerInfo.nodeType
        if (nodeType === '0') {
          modal.warn({ title: '提示', content: '不能选择节点操作' })
          return
        }
        const roleIds = []
        const checkedRole = this.$refs.roleListTable.getCheckboxRecords()
        const selectReserveRecords = this.$refs.roleListTable.getCheckboxReserveRecords()
        if (checkedRole && checkedRole.length > 0) {
          checkedRole.forEach((item) => {
            roleIds.push(item.roleId)
          })
        }
        if (selectReserveRecords && selectReserveRecords.length > 0) {
          selectReserveRecords.forEach((item) => {
            roleIds.push(item.roleId)
          })
        }
        if (roleIds.length > 0) {
          const params = {}
          params.roleIds = roleIds
          params.routerId = this.routerInfo.routerId
          setTimeout(() => {
            this.$http.post(deleteRouterRole,params).then(() => {
              modal.info({ title: '成功提示', content: '删除成功' })
              this.findRoleList()
            }).catch(() => {
            })
          }, 10)
        } else {
          modal.warn({ title: '提示', content: '请先勾选需要删除的角色' })
        }
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的路由' })
      }
    },
    clearUserAll () {
      this.queryUserParam = {}
      this.findUserList()
      setTimeout(() => {
        this.$refs.userListTable.clearSelection()
        this.$refs.userListTable.clearSelectReserve()
      }, 50)
    },
    clearRoleAll () {
      this.queryRoleParam = {}
      this.findRoleList()
      setTimeout(() => {
        this.$refs.roleListTable.clearSelection()
        this.$refs.roleListTable.clearSelectReserve()
      }, 50)
    }
  }
}
</script>
<style lang="less" scoped>
@import "~ant-design-vue/lib/style/themes/default.less";
.search-tree-color {
  color : @primary-color
}
</style>
